export default function useTime() {
  let timer
  const year = ref(null)
  const month = ref(null)
  const week = ref(null)
  const day = ref(null)
  const hour = ref(0)
  const minute = ref(0)
  const second = ref(0)

  updateTime()

  onMounted(() => {
    clearInterval(timer)
    timer = setInterval(() => updateTime(), 1000)
  })

  onUnmounted(() => clearInterval(timer))

  function updateTime() {
    const date = new Date()
    year.value = date.getFullYear()
    month.value = date.getMonth() + 1
    week.value = '日一二三四五六'.charAt(date.getDay())
    day.value = date.getDate()
    hour.value =
      `${date.getHours()}`?.padStart(2, '0') ||
      new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(date.getHours())
    minute.value =
      `${date.getMinutes()}`?.padStart(2, '0') ||
      new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(date.getMinutes())
    second.value = date.getSeconds()
  }

  return {
    year,
    month,
    week,
    day,
    hour,
    minute,
    second,
  }
}
